#include <stdio.h>  
#include <stdlib.h>  
  
// 观察者结构体  
typedef struct Observer {  
    struct Observer *next;  
    void (*update)(struct Observer *observer, int data);  
} Observer;  
  
// 附加观察者  
void attach(Observer **head, Observer *observer) {  
    observer->next = *head;  
    *head = observer;  
}  
  
// 通知所有观察者  
void notifyObservers(Observer *head, int data) {  
    Observer *current = head;  
    while (current != NULL) {  
        current->update(current, data);  
        current = current->next;  
    }  
}  
  
// 具体的观察者实现  
typedef struct ConcreteObserver {  
    Observer base;  
    // 可能的额外字段  
} ConcreteObserver;  
  
void ObserverUpdateLCD(Observer *observer, int data) {  
    ConcreteObserver *concreteObserver = (ConcreteObserver *)observer;  
    printf("LCD received data: %d\n", data);  
}
void ObserverUpdateAlarm(Observer *observer, int data) {  
    ConcreteObserver *concreteObserver = (ConcreteObserver *)observer;  
    printf("Alarm received data: %d\n", data);  
}  

// 假设我们有一个专门用于湿度的观察者  
void ObserverUpdateHumidityDisplay(Observer *observer, int data) {  
    ConcreteObserver *concreteObserver = (ConcreteObserver *)observer;  
    printf("Humidity Display received data: %d%%\n", data);  
} 
  
// 创建具体的观察者  
ConcreteObserver *createConcreteObserver(void (*update)(struct Observer *observer, int data)) {  
    ConcreteObserver *observer = (ConcreteObserver *)malloc(sizeof(ConcreteObserver));  
    if (observer) {  
        observer->base.update = update;  
        observer->base.next = NULL;  
    }  
    return observer;  
}  
  
// 主题结构体  
typedef struct Subject {  
    Observer *observers;  
    void (*notify)(struct Subject *subject, int data);  
} Subject;  
  
// 通知方法实现  
void subjectNotify(Subject *subject, int data) {  
    notifyObservers(subject->observers, data);  
}  
  
// 初始化主题  
void initSubject(Subject *subject) {  
    subject->observers = NULL;  
    subject->notify = subjectNotify;  
}  
  
int main() {  
    Subject subject;  
    initSubject(&subject);  
  
    ConcreteObserver *obs1 = createConcreteObserver(ObserverUpdateLCD);  
    ConcreteObserver *obs2 = createConcreteObserver(ObserverUpdateAlarm);  
  
    attach(&subject.observers, &obs1->base);  
    attach(&subject.observers, &obs2->base);  
  
    subject.notify(&subject, 42); // 主题通知所有观察者  
	
	Subject humiditySubject;  
	initSubject(&humiditySubject); 
	
	// 创建湿度观察者  
    ConcreteObserver *humidityDisplay = createConcreteObserver(ObserverUpdateHumidityDisplay);  
  
    // 注册湿度观察者  
    attach(&humiditySubject.observers, &humidityDisplay->base);  
  
    // 通知湿度观察者（假设湿度变化为75%）  
	humiditySubject.notify(&humiditySubject, 75);
  
    // 清理资源  
    // ...  
  
    return 0;  
}